package com.tanhua.server.Interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FreezingUser;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FreezeApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class FreezeInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private FreezeApi freezeApi;

    private static final String REDIS_KEY = "FREEZE_USER_";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始拦截");
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            long userId = UserHolder.getUserId();
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String freezeUser = ops.get(REDIS_KEY + userId);

            Integer type=0;
            //判断访问的路径
            String servletPath = request.getServletPath();
            if ("comments".equalsIgnoreCase(servletPath)||"/comments".equalsIgnoreCase(servletPath)){
                type=2;
            }else {
                type=3;
            }
            //查看redis
            if (StringUtils.isEmpty(freezeUser)) {
                //如果redis中不存在，去mongodb里面查找是否存在封号
                return freezeApi.queryById(userId, type);
            }
            FreezingUser freezingUser = JSON.parseObject(freezeUser, FreezingUser.class);
            if (freezingUser.getFreezingRange().equals(type)) {
               throw  new RuntimeException("你的账号已经冻结了...");
            }
        }
        return true;
    }
}
